<template>
  <div>
    <el-form :model="ruleForm" :rules="ruleForm.rules" ref="ruleForm" class="demo-ruleForm" style="padding: 0 10px;">
      <div style="font-size: 12px;color: #333333;margin: 5px 0px;">
        <span style="color: #f94e4e">*</span>
        {{ isenter? '入库产品': '出库产品' }}
      </div>
      <span style="top:0;right: 20px;position: absolute;">
        <psi-relative-product
          :storehouse="storehouse"
          :disabled="disable"
          :page-type="psiType"
          :batch-product="true"
          @value-change="batchProductValue"/>
      </span>
<!--      <span class="sizeAdd">+添加产品</span>-->
      <el-table
        ref="productTable"
        :data="ruleForm.tableData"
        border
        style="width: 100%;">
        <el-table-column
          fixed
          type="index"
          width="30">
        </el-table-column>
        <el-table-column fixed label="产品名称" prop="productName" width="130">
          <template slot-scope="scope">
            <el-form-item
              prop="productName"
              style="margin-bottom: 0">
              <psi-relative-product
                :storehouse="storehouse"
                :product-id="scope.row.productId"
                :value="scope.row.productNameData"
                :disabled="disable"
                :page-type="psiType"
                @table-layout = "tableLayout"
                @value-change = "getProduct($event, scope.row,scope.$index)"></psi-relative-product>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="产品编号" prop="productNum" width="130">
        </el-table-column>
        <el-table-column label="规格" prop="productSpecName" width="130">
        </el-table-column>
        <el-table-column label="产品状态" prop="productStatus" width="130">
          <template slot-scope="scope">
            <el-form-item
              style="margin-bottom: 0">
              <el-select v-model="scope.row.productStatus" placeholder="请选择" :disabled="checkFinal">
                <el-option
                  v-for="idx in options"
                  :key="idx.value"
                  :label="idx.label"
                  :value="idx.value">
                </el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="isenter? '入库数量': '出库数量'" prop="elsQuantity" width="180">
          <template slot-scope="scope">
            <el-form-item
              style="margin-bottom: 0">
              <div>
                <el-input v-model="scope.row.elsQuantity"
                          type="number"
                          :disabled="checkFinal"
                          min="1"
                          @change="changeCode(scope.row)"
                          @input="blanceNum(scope.row)">
<!--                  <template slot="append"><span title="点击开启条码录入" @click="isInputCode(scope.row)">开启</span></template>-->
                </el-input>
              </div>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="库存余量" prop="balance" width="130">
          <template slot-scope="scope">
            <el-form-item
              style="margin-bottom: 0">
              <el-input
                v-model="scope.row.balance"
                disabled
              ></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="产品条码" prop="upcCode" width="130">
          <template slot-scope="scope">
            <el-form-item
              style="margin-bottom: 0">
              <el-input
                v-for="(coseItem, codeIdx) in scope.row.upcCode"
                v-model="coseItem.barcode"
                :key="codeIdx"
                :ref="'inputCode'+ scope.$index + codeIdx"
                :class="[coseItem.barcode === null ? 'producrCodes' : '']"
                :disabled="scope.row.isShowCode"
                @keydown.enter.native="focusNextInput(coseItem, codeIdx, scope, $event, scope.$index)"
                placeholder="扫码录入条码"
              ></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remarks" width="130">
          <template slot-scope="scope">
            <el-form-item
              style="margin-bottom: 0">
              <el-input
                :disabled="checkFinal"
                v-model="scope.row.remarks"
              ></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="批次号" prop="batchId" width="130">
          <template slot-scope="scope">
            <el-form-item
              style="margin-bottom: 0">
              <el-input
                :disabled="checkFinal"
                v-model="scope.row.batchId"
              ></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="生产日期" prop="productionDate" width="163px">
          <template slot-scope="scope">
            <el-form-item
              style="margin-bottom: 0">
              <el-date-picker
                :disabled="checkFinal"
                v-model="scope.row.productionDate"
                type="date"
                placeholder="选择日期"
                style="width: 140px">
              </el-date-picker>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="失效日期" prop="expiryDate" width="163px">
          <template slot-scope="scope">
            <el-form-item
              style="margin-bottom: 0">
              <el-date-picker
                :disabled="checkFinal"
                v-model="scope.row.expiryDate"
                type="date"
                placeholder="选择日期"
                style="width: 140px">
              </el-date-picker>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="单位" prop="productUnit" width="130">
          <template slot-scope="scope">
            <el-form-item
              style="margin-bottom: 0">
              <el-select v-model="scope.row.productUnit" placeholder="请选择" disabled>
                <el-option
                  v-for="idx in options"
                  :key="idx.value"
                  :label="idx.label"
                  :value="idx.value">
                </el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          width="36">
          <template slot-scope="scope">
            <el-button
              @click.native.prevent="deleteRow(scope.$index, ruleForm.tableData)"
              type="text"
              size="small"
              :disabled="scope.$index === 0">
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <span class="sizeAdd" :class="checkFinal?'disableAdd':''" @click="addEnterPro">+添加</span>
    </el-form>
  </div>
</template>

<script>
import { psiEnterLeaveStockpileList } from '@/api/psimanagement/common'
import { XhDate, XhInput } from '@/components/CreateCom'
import PsiRelativeProduct from '@/components/CreateCom/PsiRelativeProduct'
export default {
  name: 'StoreProduct',
  components: {
    PsiRelativeProduct,
    XhDate,
    XhInput
  },
  props: {
    storehouse: {
      type: [String, Number],
      default: ''
    },
    action: {
      type: Object, default: () => {
        return {
          type: 'ave',
          id: '',
          data: {} // 编辑所需信息
        }
      }
    },
    psiType: {
      type: String,
      default: ''
    },
    isenter: {
      type: Boolean,
      default: true
    },
    isleave: {
      type: Boolean,
      default: false
    },
    checkFinal: {// 是否是审批是的产品
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      disable: true,
      isShowCode: true,
      rowAndClo: {},
      ruleForm: {
        rules: {
          productName: [
            { required: true, message: '请选择产品', trigger: 'change' }
          ],
          elsQuantity: [
            { required: true, message: '请输入入库数量', trigger: 'blur' }
          ]
        },
        tableData: []
      },
      // 选择
      options: [{
        value: '良品',
        label: '良品'
      }, {
        value: '不良品',
        label: '不良品'
      }],
      value: '',
      value1: '',
      productNameData: []
    }
  },
  watch: {
    storehouse: function(val) {
      if (val === '') {
        this.ruleForm.tableData = [{
          stockpileId: '', // 库存商品ID
          productName: '', // 产品名称
          productNameData: [],
          productId: '', // 产品ID
          storehouseId: '',
          storehouseName: '',
          elsQuantity: 1, // 出入库数量
          productNum: '', // 产品编号
          productSpecName: '', // 产品规格
          upcCodeUniqueFlag: '',
          productStatus: '良品', // 产品状态(名字)
          upcCode: [{ barcode: '' }], // 产品条码(序列号)
          remarks: '', // 备注
          batchId: '', // 批次号
          productionDate: '', // 生产日期
          expiryDate: '', // 失效日期
          productUnit: '', // 产品单位
          balance: 0, // 库存余量
          inQuantity: 0,
          isShowCode: true
        }]
      }
    }
  },
  mounted() {
    this.getDetail()
  },
  methods: {
    getDetail() {
      this.productNameData = []
      var self = this
      const reqeust = psiEnterLeaveStockpileList
      const params = {}
      params.elsId = this.action.id
      reqeust(params)
        .then(res => {
          if (res.data != '') {
            var newTableData = []
            for (var i = 0; i < res.data.length; i++) {
              var item = res.data[i]
              res.data[i]['productNameData'] = [{ productName: res.data[i].productName, productId: res.data[i].productId }]
              var idIndex = newTableData.indexOf(item.productId)
              if (idIndex != -1) {
                self.ruleForm.tableData[idIndex].upcCode.push({ barcode: item.upcCode })
                self.ruleForm.tableData[idIndex].elsQuantity = self.ruleForm.tableData[idIndex].elsQuantity + item.elsQuantity
              } else {
                newTableData.push(item.productId)
                if (item.upcCodeUniqueFlag === 1) {
                  item['isShowCode'] = false
                } else {
                  item['isShowCode'] = true
                }
                item.upcCode = [{ barcode: item.upcCode }]
                self.ruleForm.tableData.push(item)
              }
            }
            for (var i = 0; i < self.ruleForm.tableData.length; i++) {
              var item = self.ruleForm.tableData[i]
              item['inQuantity'] = item.balance - Number(item.elsQuantity)
            }
            if (this.checkFinal) {
              this.disable = true
            } else {
              this.disable = false
            }
          } else {
            self.ruleForm.tableData.push({
              stockpileId: '', // 库存商品ID
              productName: '', // 产品名称
              productNameData: [],
              productId: '', // 产品ID
              storehouseId: '',
              storehouseName: '',
              elsQuantity: 1, // 出入库数量
              productNum: '', // 产品编号
              productSpecName: '', // 产品规格
              upcCodeUniqueFlag: '',
              productStatus: '良品', // 产品状态(名字)
              upcCode: [{ barcode: '' }], // 产品条码(序列号)
              remarks: '', // 备注
              batchId: '', // 批次号
              productionDate: '', // 生产日期
              expiryDate: '', // 失效日期
              productUnit: '', // 产品单位
              balance: 0, // 库存余量
              inQuantity: 0,
              isShowCode: true
            })
            this.disable = true
          }
        })
        .catch(() => {})
    },
    isInputCode(item) {
      var havecode = []
      for (var i = 0; i < item.upcCode.length; i++) {
        if (item.upcCode[i].barcode != '') {
          havecode.push(item.upcCode[i])
        }
      }
      if (havecode.length > Number(item.elsQuantity)) {
        havecode.splice(Number(item.elsQuantity), havecode.length - Number(item.elsQuantity))
      } else {
        var num = Number(item.elsQuantity) - havecode.length
        for (var i = 0; i < num; i++) {
          havecode.push({ barcode: '' })
        }
      }
      item.upcCode = havecode
    },
    // 获取出入库的产品
    getProduct(data, item, index) {
      if (data.value.length > 0) {
        if (data.value[0].upcCodeUniqueFlag === 1) {
          item.isShowCode = false
        } else {
          item.isShowCode = true
        }
        var time = new Date()
        item.stockpileId = data.value[0].stockpileId
        item.storehouseId = data.value[0].storehouseId
        item.storehouseName = data.value[0].storehouseName
        item.upcCode[0].barcode = data.value[0].upcCode
        item.productId = data.value[0].productId
        item.productName = data.value[0].productName
        item.productNum = data.value[0].num
        item.productSpecName = data.value[0].specName
        item.upcCodeUniqueFlag = data.value[0].upcCodeUniqueFlag
        item.productUnit = data.value[0].unit
        item.inQuantity = data.value[0].quantity
        item['description'] = data.value[0].description
        item.productionDate = time
        if (this.isenter) {
          item.balance = Number(item.elsQuantity) + Number(data.value[0].quantity)
        } else if (this.isleave) {
          item.balance = Number(data.value[0].quantity) - Number(item.elsQuantity)
        }
      } else {
        item.stockpileId = ''
        item.storehouseId = ''
        item.storehouseName = ''
        item.upcCode = [{ barcode: '' }]
        item.productId = ''
        item.productName = ''
        item.productNum = ''
        item.productSpecName = ''
        item.upcCodeUniqueFlag = ''
        item.productUnit = ''
        item.inQuantity = ''
        item['description'] = ''
        item.productionDate = ''
        item.balance = Number(item.balance) - Number(item.elsQuantity)
        item.elsQuantity = 1
      }
    },
    // 批量添加
    batchProductValue(data) {
      if (this.ruleForm.tableData.length === 1 && this.ruleForm.tableData[0].productName == '') {
        var arry = []
        var time = new Date()
        for (var i = 0; i < data.value.length; i++) {
          arry.push({
            stockpileId: data.value[i].stockpileId, // 库存商品ID
            productName: data.value[i].productName, // 产品名称
            productNameData: [{ productName: data.value[i].productName, productId: data.value[i].productId }],
            productId: data.value[i].productId, // 产品ID
            storehouseId: data.value[i].storehouseId,
            storehouseName: data.value[i].storehouseName,
            elsQuantity: 1, // 出入库数量
            productNum: data.value[i].num, // 产品编号
            productSpecName: data.value[i].specName, // 产品规格
            upcCodeUniqueFlag: data.value[i].upcCodeUniqueFlag,
            productStatus: '良品', // 产品状态(名字)
            upcCode: [{ barcode: '' }], // 产品条码(序列号)
            remarks: '', // 备注
            batchId: '', // 批次号
            productionDate: time, // 生产日期
            expiryDate: '', // 失效日期
            productUnit: data.value[i].unit, // 产品单位
            balance: 0, // 库存余量
            inQuantity: data.value[i].quantity,
            isShowCode: true })
          if (this.isenter) {
            arry[i].balance = Number(arry[i].elsQuantity) + Number(data.value[i].quantity)
          } else if (this.isleave) {
            arry[i].balance = Number(data.value[i].quantity) - Number(arry[i].elsQuantity)
          }
          if (data.value[i].upcCodeUniqueFlag === 1) {
            arry[i].isShowCode = false
          } else {
            arry[i].isShowCode = true
          }
        }
        this.ruleForm.tableData = arry
      } else {
        var time = new Date()
        for (var i = 0; i < data.value.length; i++) {
          var pushArry = true
          for (var idx = 0; idx < this.ruleForm.tableData.length; idx++) {
            if (data.value[i].productId == this.ruleForm.tableData[idx].productId && data.value[i].specName == this.ruleForm.tableData[idx].productSpecName) {
              pushArry = false
            }
          }
          if (pushArry) {
            this.ruleForm.tableData.push({
              stockpileId: data.value[i].stockpileId, // 库存商品ID
              productName: data.value[i].productName, // 产品名称
              productNameData: [{ productName: data.value[i].productName, productId: data.value[i].productId }],
              productId: data.value[i].productId, // 产品ID
              storehouseId: data.value[i].storehouseId,
              storehouseName: data.value[i].storehouseName,
              elsQuantity: 1, // 出入库数量
              productNum: data.value[i].num, // 产品编号
              productSpecName: data.value[i].specName, // 产品规格
              upcCodeUniqueFlag: data.value[i].upcCodeUniqueFlag,
              productStatus: '良品', // 产品状态(名字)
              upcCode: [{ barcode: '' }], // 产品条码(序列号)
              remarks: '', // 备注
              batchId: '', // 批次号
              productionDate: time, // 生产日期
              expiryDate: '', // 失效日期
              productUnit: data.value[i].unit, // 产品单位
              balance: this.isenter ? 1 + Number(data.value[i].quantity) : Number(data.value[i].quantity) - 1, // 库存余量
              inQuantity: data.value[i].quantity,
              isShowCode: (data.value[i].upcCodeUniqueFlag === 1)?false:true })
          }
        }
      }
    },
    addEnterPro() {
      if (this.checkFinal) {
        return false
      }
      this.ruleForm.tableData.push({
        stockpileId: '', // 库存商品ID
        productName: '', // 产品名称
        productId: '', // 产品ID
        storehouseId: '',
        storehouseName: '',
        elsQuantity: 1, // 出入库数量
        productNum: '', // 产品编号
        productSpecName: '', // 产品规格
        upcCodeUniqueFlag: '',
        productStatus: '良品', // 产品状态(名字)
        // 库存数量
        upcCode: [{ barcode: '' }], // 产品条码(序列号)
        remarks: '', // 备注
        batchId: '', // 批次号
        productionDate: '', // 生产日期
        expiryDate: '', // 失效日期
        productUnit: '', // 产品单位
        balance: 0,
        inQuantity: 0,
        isShowCode: true
      })
    },
    blanceNum(data) {
      if (this.isenter) {
        data.balance = Number(data.elsQuantity) + Number(data.inQuantity)
      } else if (this.isleave) {
        data.balance = Number(data.inQuantity) - Number(data.elsQuantity)
      }
    },
    changeCode(data) { // 改变产品条码的个数
      if (data.upcCodeUniqueFlag == 1) {
        this.isInputCode(data)
      }
    },
    focusNextInput(item, index, scope, e, scInput) {
      if (this.$refs['inputCode' + scInput + index]) {
        this.$nextTick(() => {
          var idxStr = item.barcode.lastIndexOf('\=')
          item.barcode = item.barcode.substring(idxStr + 1, item.barcode.length)
          e.target.blur()
          var idx = index + 1
          if (idx == scope.row.upcCode.length) {
            var scIdx = scInput + 1
            if (this.ruleForm.tableData.length == scIdx) {
              return
            }
            this.$refs['inputCode' + scIdx + '0'][0].focus()
          } else {
            this.$refs['inputCode' + scInput + idx][0].focus()
          }
        })
      }
    },
    // 选择产品后重新布局
    tableLayout(val) {
      if (this.checkFinal) {
        this.disable = true
      } else {
        this.disable = val
      }
    },
    deleteRow(index, rows) {
      rows.splice(index, 1)
    }
  }
}
</script>

<style scoped>
  .sizeAdd{
    display: inline-block;
    margin: 5px 0;
    color: #3c8be3;
    cursor: pointer;
  }
  .disableAdd{
    color: #c2c2c2;
    cursor: not-allowed;
  }
</style>
<style>
  .producrCodes>.el-input__inner{
    border-color: red!important;
  }
</style>
